const express = require('express');
const expressWs = require('express-ws');
const cors = require('cors');
const ResponseData = require('./ResponseData');
const bodyParser = require('body-parser');
const port = 5269;
const app = express();

app.use(cors());

expressWs(app);

app.use(bodyParser.json());


// 保存当前连接信息
const sessionClient = {};

/**
 * 校验验证码是否扫描 -- 也可以直接在前端使用 websocket 通知，我这里就用请求的方式
 */
app.post('/api/login_code', (req, res) => {
    const { to, isCode } = req.body;
    sessionClient[to][0].send(JSON.stringify({ code: 101, data: { isCode }, message: 'success', date: new Date() }))
    res.send(ResponseData.success({ isCode: true }))
})

app.post('/api/login', (req, res) => {
    const { username, mode, to } = req.body;
    // 根据自己的业务逻辑，我这里只判断是不是 CODE 模式登录，也可以单独写接口
    if (mode === 'CODE') {
        sessionClient[to][0].send(JSON.stringify({ code: 101, data: { token: Math.random(), username }, message: 'success', date: new Date() }))
    } else {
        res.send(ResponseData.success({ token: Math.random() }))
    }
})

app.ws('/login/:to', (ws, req) => {
    const toInfo = req.params.to;
    if (!sessionClient[toInfo]) {
        sessionClient[toInfo] = [];
    }

    sessionClient[toInfo].push(ws);

    ws.on('message', () => {
        console.log('req', req);
        console.log(arguments);
    })

    ws.on('close', () => {
        if (sessionClient[toInfo]) {
            delete sessionClient[toInfo];
        }
    })
})

app.listen(port, () => { console.log(`express server listen at http://localhost:${port}`) })